﻿//-----------------------------------------------------------------------
// <copyright file="TokenBasedView.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.ContactManager.WebSite.Infrastructure.ViewEngines
{
    using System.IO;
    using System.Web.Mvc;

    public class TokenBasedView : IView
    {
        private readonly string viewPath;

        public TokenBasedView(string viewPath)
        {
            this.viewPath = viewPath;
        }

        #region Implementation of IView

        public void Render(ViewContext viewContext, TextWriter writer)
        {
            string filePath = viewContext.HttpContext.Server.MapPath(this.viewPath);

            string fileContents = File.ReadAllText(filePath);

            var model = viewContext.ViewData.Model;
            foreach(var property in model.GetType().GetProperties())
            {
                if (typeof(System.ValueType).IsAssignableFrom(property.PropertyType) || property.PropertyType.Equals(typeof(string)))
                {
                    var propertyValue = property.GetValue(model, new object[] {});
                    fileContents = fileContents.Replace("{" + property.Name + "}", propertyValue.ToString());
                }   
            }   
            writer.Write(fileContents);
        }

        #endregion
    }
}